var(可能會衝突)當使用 var 在全域範圍內宣告變數時,這些變數會成為全域物件(在瀏覽器中是 window 物件)的屬性,這可能導致變數名稱衝突:
例如:
var name = "MyApp"; // 假設這是你的應用程式
var name = "AnotherScript"; // 第三方腳本可能覆寫你的變數
console.log(name); // 輸出 "AnotherScript",而不是 "MyApp"
let(避免變數污染)使用 let 宣告的變數具有區塊作用域,不會成為全域物件的屬性,從而避免了全域變數污染:
let 宣告的變數不會添加到全域物件(如 window)中例如:
let name = "MyApp"; // 這不會影響全域物件
{ let name = "LocalName"; console.log(name); } // 輸出 "LocalName"
console.log(name); // 輸出 "MyApp",不受區塊內變數影響